package com.itfreer.file.client;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.ListBucketsRequest;
import com.itfreer.file.service.IBucketManageService;

/**
 * 定义文件块存储接口
 */
@Component
public class OssBucketManage implements IBucketManageService, BeanFactoryAware {
	
	protected static BeanFactory beanFactory;

	@Override
	public void setBeanFactory(BeanFactory bf) throws BeansException {
		beanFactory = bf;
	}
	
	private AliyunOssPara aliyunOssPara;
	
	private AliyunOssPara getPara(){
		if(aliyunOssPara==null){
			aliyunOssPara = (AliyunOssPara) beanFactory.getBean("aliyunOssPara");
		}
		return aliyunOssPara;
	}
	
	private OSSClient getClient(){
		OSSClient ossClient = new OSSClient(getPara().getEndpoint(), getPara().getAccessKeyId(), getPara().getAccessKeySecret());
		return ossClient;
	}

	/**
	 * 创建文件存储块
	 * @param bucketName
	 */
	public void createBucket(String bucketName){
		// 创建OSSClient实例
		OSSClient ossClient = getClient();
		// 创建bucket
		ossClient.createBucket(bucketName);
		// 关闭client
		ossClient.shutdown();
	}
	
	/**
	 * 列举Bucket
	 * @param prefix  限定返回的bucket name必须以prefix作为前缀，可以不设定，不设定时不过滤前缀信息
	 * @param marker  设定结果从marker之后按字母排序的第一个开始返回，可以不设定，不设定时从头开始返回
	 * @param maxKeys 限定此次返回bucket的最大数，如果不设定，默认为100，max-keys取值不能大于1000
	 * @return
	 */
	public List<String> listBuckets(String prefix, String marker, Integer maxKeys){
		// 创建OSSClient实例
		OSSClient ossClient = getClient();

		ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
		if(maxKeys!=null){
			listBucketsRequest.setMaxKeys(maxKeys);
		}
		if(prefix!=null){
			listBucketsRequest.setPrefix(prefix);
		}
		if(marker!=null){
			listBucketsRequest.setMarker(marker);
		}
		
		List<String> bucketNames = new ArrayList<String>();
		// 列举bucket
		List<Bucket> buckets = ossClient.listBuckets();
		for (Bucket bucket : buckets) {
			bucketNames.add(bucket.getName());
		}
		// 关闭client
		ossClient.shutdown();
		return bucketNames;
	}
	
	/**
	 * 删除文件存储块
	 * @param bucketName
	 */
	public void deleteBucket(String bucketName){
		// 创建OSSClient实例
		OSSClient ossClient = getClient();
		// 删除bucket
		ossClient.deleteBucket(bucketName);
		// 关闭client
		ossClient.shutdown();
	}
	
	/**
	 * 文件存储块是否存在
	 * @param bucketName
	 */
	public boolean doesBucketExist(String bucketName){
		// 创建OSSClient实例
		OSSClient ossClient = getClient();
		boolean exists = ossClient.doesBucketExist(bucketName);
		// 关闭client
		ossClient.shutdown();
		return exists;
	}
}
